package com.peas.platform.module.icims;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.SneakyThrows;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 图片转pdf工具类
 */
public class ImgToPdfUtil {

    @SneakyThrows
    public File Pdf(List<String> imageUrllist, String mOutputPdfFileName) {
        Document doc = new Document(PageSize.A4, 0, 0, 0, 0); //new一个pdf文档
        PdfWriter.getInstance(doc, Files.newOutputStream(Paths.get(mOutputPdfFileName))); //pdf写入
        doc.open();//打开文档
        for (String s : imageUrllist) {  //循环图片List，将图片加入到pdf中
            doc.newPage();  //在pdf创建一页
            Image png1 = Image.getInstance(s); //通过文件路径获取image
            float height = png1.getHeight();
            float width = png1.getWidth();
            int percent = getPercent2(height, width);
            png1.setAlignment(Image.MIDDLE);
            png1.scalePercent(percent + 3);// 表示是原来图像的比例;
            doc.add(png1);
        }
        doc.close();
        File mOutputPdfFile = new File(mOutputPdfFileName);  //输出流
        if (!mOutputPdfFile.exists()) {
            mOutputPdfFile.deleteOnExit();
            return null;
        }
        return mOutputPdfFile; //反回文件输出流
    }

    public static int getPercent(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        if (h > w) {
            p2 = 297 / h * 100;
        } else {
            p2 = 210 / w * 100;
        }
        p = Math.round(p2);
        return p;
    }

    public static int getPercent2(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;
    }

    @SneakyThrows
    public void imgOfPdf(String filepath, List<String> imageUrllist) {
        File file = Pdf(imageUrllist, filepath);//生成pdf
        if (file != null) {
            file.createNewFile();
        }
    }

    public static void main(String[] args) {
        ImgToPdfUtil img = new ImgToPdfUtil();
        File root = new File("/Users/caizhaohui/Documents/99");
        List<File> dirs = Arrays.asList(Objects.requireNonNull(root.listFiles()));
        dirs.sort(Comparator.comparing(File::getPath));
        List<String> all = new ArrayList<>();
        for (File dir : dirs) {
            if (!dir.isDirectory()) {
                continue;
            }
            List<File> files = Arrays.asList(Objects.requireNonNull(dir.listFiles()));
            files.sort(Comparator.comparing(File::getPath));
            all.addAll(files.stream().filter(file -> file.getName().toLowerCase().endsWith(".jpg")).map(File::getPath).collect(Collectors.toList()));
        }
        all.forEach(System.out::println);
        img.imgOfPdf("/Users/caizhaohui/Documents/99/99.pdf", all);
    }
}

